package com.captain.special.位运算;

/**
 * @author YangXiaoLong
 * 2022/12/2 9:20
 */
public class 二进制求和67 {
    public static String addBinary(String a, String b) {
        int al = a.length();
        int bl = b.length();
        int loopLen = al;
        if (al < bl) {
            loopLen = bl;
        }
        int alDifference = loopLen - al;
        int blDifference = loopLen - bl;
        StringBuilder builder = new StringBuilder();
        int carryVal = 0;
        for (int len = loopLen - 1; len >= 0; len--) {
            int blIndex = len - blDifference;
            int alIndex = len - alDifference;
            String ac = "0";
            if (alIndex >= 0) {
                ac = a.charAt(alIndex) + "";
            }
            String bc = "0";
            if (blIndex >= 0) {
                bc = b.charAt(blIndex) + "";
            }
            int curVal = (Integer.parseInt(ac) + Integer.parseInt(bc)) + carryVal;
            switch (curVal) {
                case 0:
                    builder.append("0");
                    carryVal = 0;
                    break;
                case 1:
                    builder.append("1");
                    carryVal = 0;
                    break;
                case 2:
                    builder.append("0");
                    carryVal = 1;
                    break;
                default:
                    builder.append("1");
                    carryVal = 1;
            }
        }
        if (carryVal > 0) {
            builder.append("1");
        }
        return builder.reverse().toString();
    }
}
